//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.hustcad.plm.pdm.partbom.service.impl.partalternate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.hustcad.plm.basic.util.TyCommonExtUtil;
import com.hustcad.plm.basic.util.TyplmLoggerUtil;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.common.util.TyplmPermissionsUtil;
import com.hustcad.plm.pdm.enumeration.service.TyplmLocalePropertyValueService;
import com.hustcad.plm.pdm.iba.model.dto.IBASaveParamDTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.iba.service.TyplmCommonAttributeService;
import com.hustcad.plm.pdm.iteration.service.TyplmCommonIterateService;
import com.hustcad.plm.pdm.partbom.dto.QuerySubstituteLinkDTO;
import com.hustcad.plm.pdm.partbom.dto.TyplmUpdateLinkIbaDTO;
import com.hustcad.plm.pdm.partbom.enums.PartBomErrorCodeEnum;
import com.hustcad.plm.pdm.partbom.service.TyplmPartAlterLinkSaveService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartAlternateService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartMasterExtService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.service.partalternate.TyplmPdmPartAlternateService;
import com.hustcad.plm.pdm.partbom.service.partalternate.TyplmPdmPartSubstituteService;
import com.hustcad.plm.pdm.partbom.vo.AlternateForInfoVO;
import com.hustcad.plm.pdm.partbom.vo.AlternateInfoVO;
import com.hustcad.plm.pdm.partbom.vo.PartAlterLinkVO;
import com.hustcad.plm.pdm.partbom.vo.PartSubstituteVO;
import com.hustcad.plm.pdm.partbom.vo.TyPartAllVO;
import com.hustcad.plm.pdm.partbom.vo.virtualpart.PartAlterLinkResultVO;
import com.hustcad.plm.pdm.type.model.vo.TypeVueVO;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.part.PartAlterLinkDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.part.PartMasterDO;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.util.StringUtil;
import com.ty.basic.vo.AttributeVO;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TyplmPdmPartAlternateServiceImpl implements TyplmPdmPartAlternateService {
    private static final Logger log = LoggerFactory.getLogger(TyplmPdmPartAlternateServiceImpl.class);
    @Resource
    private TyplmPartAlternateService typlmPartAlternateService;
    @Resource
    private TyplmPartService typlmPartService;
    @Resource
    private TyplmPartMasterExtService typlmPartMasterExtService;
    @Resource
    private TyplmPartAlterLinkSaveService typlmPartAlterLinkSaveService;
    @Resource
    private TyplmPdmPartSubstituteService typlmPdmPartSubstituteService;
    @Resource
    private TyplmLocalePropertyValueService typlmLocalePropertyValueService;
    @Resource
    private TyplmPermissionsUtil typlmPermissionsUtil;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmCommonIterateService typlmCommonIterateService;
    @Resource
    private TyplmCommonAttributeService typlmCommonAttributeService;
    @Resource
    private TyplmTypeService typlmTypeService;

    public TyplmPdmPartAlternateServiceImpl() {
    }

    public List<AlternateInfoVO> batchQueryAlternates(List<String> alternateForPartNumbers) throws ParseException {
        List<AlternateInfoVO> result = new ArrayList();
        List<AlternateInfoVO> alternateInfoVOS = this.typlmPartAlternateService.batchQueryAlternates(alternateForPartNumbers);
        if (CollUtil.isEmpty(alternateInfoVOS)) {
            return new ArrayList();
        } else {
            List<String> numberList = (List)alternateInfoVOS.stream().map(AlternateInfoVO::getAlternateObjectNumber).collect(Collectors.toList());
            List<String> replacementTypeCodes = (List)alternateInfoVOS.stream().map(AlternateInfoVO::getReplacementType).collect(Collectors.toList());
            List<BigInteger> linkOidList = (List)alternateInfoVOS.stream().map((obj) -> {
                return CommonUtil.stringToBigInteger(obj.getId());
            }).collect(Collectors.toList());
            Map<String, String> replacementTypeCodeNameMap = this.typlmLocalePropertyValueService.queryLocaleValueByItem(replacementTypeCodes, "ReplacementType", TyCommonExtUtil.getFrontLanguage());
            List<PartMasterDO> masterDOS = this.typlmPartMasterExtService.batchQueryPartMasterDOByNumbers(numberList);
            List<TyPartAllVO> tyPartAllVOS = this.typlmPartService.queryPartLatestByMasterIds((List)masterDOS.stream().map(PartMasterDO::getOid).collect(Collectors.toList()));
            Map<String, List<TyPartAllVO>> numberMap = (Map)tyPartAllVOS.stream().collect(Collectors.groupingBy(TyPartAllVO::getMasterPartNumber));
            List<AlternateInfoVO> alternateInfoVOSList = this.typlmPartAlternateService.batchQueryAlternates(numberList);
            Map<String, Set<String>> map = (Map)alternateInfoVOSList.stream().collect(Collectors.groupingBy(AlternateInfoVO::getAlternateForPartNumber, Collectors.mapping(AlternateInfoVO::getAlternateObjectNumber, Collectors.toSet())));
            Map<String, String> localeValueMap = this.typlmLocalePropertyValueService.queryLocaleValueByItem(new ArrayList(), "SecurityLabels", TyCommonExtUtil.getFrontLanguage());
            Map<String, List<AttributeVO>> attributeValueMap = this.typlmAttributeValueService.getAttrValueTableByEntitys(linkOidList, "ty.inteplm.part.CTyPartAlterLink");
            alternateInfoVOS.forEach((vo) -> {
                AlternateInfoVO alternateInfoVO = new AlternateInfoVO();
                BeanUtils.copyProperties(vo, alternateInfoVO);
                Set<String> numbers = (Set)map.get(vo.getAlternateObjectNumber());
                if (CollUtil.isNotEmpty(numbers) && numbers.contains(vo.getAlternateForPartNumber())) {
                    alternateInfoVO.setIsTwoWay(true);
                }

                TyPartAllVO partAllVO = (TyPartAllVO)((List)numberMap.get(vo.getAlternateObjectNumber())).get(0);
                alternateInfoVO.setAlternateObjectName(partAllVO.getMasterName());
                alternateInfoVO.setContainerName(partAllVO.getContainerName());
                alternateInfoVO.setContainerOid(partAllVO.getContaineroid());
                alternateInfoVO.setAlternateObjectMasterOid(partAllVO.getMasteredoid());
                alternateInfoVO.setSecurity((String)localeValueMap.get(partAllVO.getSecuritylabels()));
                alternateInfoVO.setReplacementTypeText(StringUtil.isNotEmpty((String)replacementTypeCodeNameMap.get(vo.getReplacementType())) ? (String)replacementTypeCodeNameMap.get(vo.getReplacementType()) : vo.getReplacementType());
                if (CollUtil.isNotEmpty(attributeValueMap) && attributeValueMap.containsKey(alternateInfoVO.getId())) {
                    List<AttributeVO> ibaAttributeList = (List)attributeValueMap.get(alternateInfoVO.getId());
                    Map<String, List<String>> ibaAttributeMap = this.typlmCommonIterateService.parseIbaMapByIbaList(ibaAttributeList);
                    alternateInfoVO.setIbaAttributeMap(ibaAttributeMap);
                    alternateInfoVO.setIbaAttributeList(ibaAttributeList);
                }

                result.add(alternateInfoVO);
            });
            return result;
        }
    }

    public List<PartAlterLinkResultVO> batchSavePartAlterLink(List<PartAlterLinkVO> partAlterLinkVOList) {
        Iterator<PartAlterLinkVO> iterator = partAlterLinkVOList.iterator();
        Map<String, String> map = new HashMap();

        while(true) {
            while(iterator.hasNext()) {
                PartAlterLinkVO linkVO = (PartAlterLinkVO)iterator.next();
                if (map.containsKey(linkVO.getAlternateForNumber()) && ((String)map.get(linkVO.getAlternateForNumber())).equalsIgnoreCase(linkVO.getAlternateNumber())) {
                    iterator.remove();
                } else {
                    map.put(linkVO.getAlternateForNumber(), linkVO.getAlternateNumber());
                }
            }

            if (CollUtil.isNotEmpty(partAlterLinkVOList)) {
                List<BigInteger> partOidList = (List)partAlterLinkVOList.stream().map(PartAlterLinkVO::getAlternateOid).collect(Collectors.toList());

                List<PartDO> partDOS = this.typlmPartService.queryPartByBigIntegerIDs(partOidList);
                List<String> permissionList = new ArrayList();
                partDOS.forEach((vo) -> {
                    permissionList.add("读取");
                });
                this.typlmPermissionsUtil.checkObjectPermissionList(TyAccountContext.getUser(), new ArrayList(partDOS), permissionList);
            }

            return this.typlmPartAlterLinkSaveService.batchSavePartAlterLink(partAlterLinkVOList);
        }
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean batchUpdatePartAlterLinkIba(List<TyplmUpdateLinkIbaDTO> typlmUpdateLinkIbaList) {
        if (CollUtil.isEmpty(typlmUpdateLinkIbaList)) {
            return Boolean.FALSE;
        } else {
            TyplmLoggerUtil.debug(log, () -> {
                return "partAlterLinkVOList  ==> 批量修改部件全局替代关联关系上扩展属性,接口入参信息 =【{}】";
            }, () -> {
                return new Object[]{JSON.toJSONString(typlmUpdateLinkIbaList)};
            });
            List<BigInteger> partAlterLinkOidList = (List)typlmUpdateLinkIbaList.stream().filter((obj) -> {
                return StringUtils.isNotBlank(obj.getLinkId());
            }).map((obj) -> {
                return CommonUtil.stringToBigInteger(obj.getLinkId());
            }).collect(Collectors.toList());
            List<PartAlterLinkDO> linkList = this.typlmPartAlterLinkSaveService.queryPartAlterLinkDOByIds(partAlterLinkOidList);
            List<IBASaveParamDTO> objWithIbaList = new ArrayList();
            BigInteger typeOid = null;
            List<TypeVueVO> typeVueVOS = this.typlmTypeService.queryTypeByNameList(Lists.newArrayList(new String[]{"ty.inteplm.part.CTyPartAlterLink"}));
            if (CollUtil.isNotEmpty(typeVueVOS)) {
                typeOid = ((TypeVueVO)typeVueVOS.get(0)).getOid();
            }

            if (ObjectUtil.isEmpty(typeOid)) {
                throw PartBomErrorCodeEnum.PARTBOM_OBJTYPE_NOT_EXIST.getException(new Object[]{"ty.inteplm.part.CTyPartAlterLink"});
            } else {
                Map<BigInteger, PartAlterLinkDO> partAlterLinkMap = (Map)linkList.stream().collect(Collectors.toMap(PartAlterLinkDO::getOid, Function.identity(), (k1, k2) -> {
                    return k1;
                }));
                Iterator var8 = typlmUpdateLinkIbaList.iterator();

                while(var8.hasNext()) {
                    TyplmUpdateLinkIbaDTO typlmUpdateLinkIbaDTO = (TyplmUpdateLinkIbaDTO)var8.next();
                    BigInteger linkOid = CommonUtil.stringToBigInteger(typlmUpdateLinkIbaDTO.getLinkId());
                    if (CollUtil.isNotEmpty(typlmUpdateLinkIbaDTO.getIbaAttributeMap())) {
                        this.typlmCommonIterateService.parseIBASaveParamDTOIbaDtoList((CTyEntityBaseDO)partAlterLinkMap.get(linkOid), typlmUpdateLinkIbaDTO.getIbaAttributeMap(), objWithIbaList, Boolean.FALSE, typeOid);
                    }
                }

                List<List<IBASaveParamDTO>> pieceList = CommonUtil.subObjectList(objWithIbaList, 200);
                Iterator var13 = pieceList.iterator();

                while(var13.hasNext()) {
                    List<IBASaveParamDTO> ibadtoList = (List)var13.next();
                    TyplmLoggerUtil.debug(log, () -> {
                        return "batchUpdatePartAlterLinkIBA  ==> 更新扩展属性集合ibadtoList =【{}】";
                    }, () -> {
                        return new Object[]{JSON.toJSONString(ibadtoList)};
                    });
                    this.typlmCommonAttributeService.batchSaveAttributeValue(ibadtoList);
                }

                return Boolean.TRUE;
            }
        }
    }

    public boolean batchDeletePartAlternateLink(List<PartAlterLinkVO> partAlterLinkVOList) throws ParseException {
        List<String> numbers = (List)partAlterLinkVOList.stream().map(PartAlterLinkVO::getAlternateForNumber).collect(Collectors.toList());
        Map<String, Set<String>> alternateForNumberMap = (Map)partAlterLinkVOList.stream().collect(Collectors.groupingBy(PartAlterLinkVO::getAlternateForNumber, Collectors.mapping(PartAlterLinkVO::getAlternateNumber, Collectors.toSet())));
        List<AlternateInfoVO> alternateInfoVOS = this.typlmPartAlternateService.batchQueryAlternates(numbers);
        List<String> idList = (List)alternateInfoVOS.stream().filter((vo) -> {
            return ((Set)alternateForNumberMap.get(vo.getAlternateForPartNumber())).contains(vo.getAlternateObjectNumber());
        }).map(AlternateInfoVO::getId).collect(Collectors.toList());
        return CollUtil.isEmpty(idList) ? true : this.typlmPartAlterLinkSaveService.batchDeletePartAlternateLink(idList);
    }

    public List<AlternateInfoVO> queryPartAllAlternate(QuerySubstituteLinkDTO querySubstituteLinkDTO) throws ParseException {
        String bnumber = querySubstituteLinkDTO.getBnumber();
        List<AlternateInfoVO> alternateInfoVOS = this.batchQueryAlternates(Collections.singletonList(bnumber));
        List<PartSubstituteVO> partSubstituteInfoVOS = this.typlmPdmPartSubstituteService.queryPartSubstituteLink(querySubstituteLinkDTO);
        partSubstituteInfoVOS.forEach((vo) -> {
            AlternateInfoVO alternateInfoVO = new AlternateInfoVO();
            alternateInfoVO.setId(vo.getLinkId());
            alternateInfoVO.setAlternateObjectName(vo.getName());
            alternateInfoVO.setAlternateObjectNumber(vo.getNumber());
            alternateInfoVO.setReplacementType(vo.getLinkReplacementTypeKey());
            alternateInfoVO.setContainerOid(vo.getContainerid());
            alternateInfoVO.setContainerName(vo.getContainerName());
            alternateInfoVO.setAlternateObjectMasterOid(CommonUtil.stringToBigInteger(vo.getMasterId()));
            alternateInfoVO.setReplacementTypeText(vo.getLinkReplacementTypeText());
            alternateInfoVOS.add(alternateInfoVO);
        });
        return alternateInfoVOS;
    }

    public List<AlternateForInfoVO> batchQueryAlternateFor(List<String> partNumberList) {
        List<AlternateForInfoVO> alternateForInfoVOList = this.typlmPartAlternateService.queryPartAlternateForByPartNumbers(partNumberList);
        if (CollUtil.isEmpty(alternateForInfoVOList)) {
            return Collections.emptyList();
        } else {
            List<BigInteger> linkOidList = (List)alternateForInfoVOList.stream().map(AlternateForInfoVO::getLinkOid).collect(Collectors.toList());
            Map<String, List<AttributeVO>> attributeValueMap = this.typlmAttributeValueService.getAttrValueTableByEntitys(linkOidList, "ty.inteplm.part.CTyPartAlterLink");
            List<String> replacementTypeCodeList = (List)alternateForInfoVOList.stream().map(AlternateForInfoVO::getReplacementType).collect(Collectors.toList());
            Map<String, String> replacementTypeCodeNameMap = (Map)ObjectUtil.defaultIfNull(this.typlmLocalePropertyValueService.queryLocaleValueByItem(replacementTypeCodeList, "ReplacementType", TyCommonExtUtil.getFrontLanguage()), Collections.emptyMap());
            List<BigInteger> masterOidList = (List)alternateForInfoVOList.stream().map(AlternateForInfoVO::getAlternateForMasterOid).filter(Objects::nonNull).collect(Collectors.toList());
            Map<String, List<TyPartAllVO>> latestPartMap;
            if (ObjectUtil.isNotEmpty(masterOidList)) {
                List<TyPartAllVO> partAllVOList = (List)ObjectUtil.defaultIfNull(this.typlmPartService.queryPartLatestByMasterIds(masterOidList), Collections.emptyList());
                latestPartMap = (Map)partAllVOList.stream().collect(Collectors.groupingBy(PartDO::getMasteredoid));
            } else {
                latestPartMap = Collections.emptyMap();
            }

            alternateForInfoVOList.forEach((t) -> {
                if (t.getAlternateForMasterOid() != null) {
                    Optional.of(latestPartMap.getOrDefault(t.getAlternateForMasterOid(), Collections.emptyList())).filter(ObjectUtil::isNotEmpty).ifPresent((p) -> {
                        t.setContainerName(((TyPartAllVO)p.get(0)).getContainerName());
                        t.setContainerOid(((TyPartAllVO)p.get(0)).getContaineroid());
                    });
                }

                t.setReplacementTypeText((String)replacementTypeCodeNameMap.getOrDefault(t.getReplacementType(), ""));
                String linkOid = String.valueOf(t.getLinkOid());
                if (CollUtil.isNotEmpty(attributeValueMap) && attributeValueMap.containsKey(linkOid)) {
                    List<AttributeVO> ibaAttributeList = (List)attributeValueMap.get(linkOid);
                    Map<String, List<String>> ibaAttributeMap = (Map)ibaAttributeList.stream().collect(Collectors.groupingBy(AttributeVO::getAttributeEnName, Collectors.mapping((iba) -> {
                        return iba.getAttributeValuex() == null ? "" : iba.getAttributeValuex();
                    }, Collectors.toList())));
                    t.setIbaAttributeMap(ibaAttributeMap);
                    t.setIbaAttributeList(ibaAttributeList);
                }

            });
            return alternateForInfoVOList;
        }
    }
}
